<template>
  <div class="common-container">
    <div class="common-header">
      <h2>互动记录管理</h2>
    </div>
    
    <!-- 查询条件和操作按钮 -->
    <div class="common-search-bar">
      <el-form :inline="true" :model="queryForm" class="common-search-form">
        <el-form-item label="互动类型">
          <el-select 
            v-model="queryForm.interactionType" 
            placeholder="请选择互动类型" 
            clearable
            style="width: 180px;"
          >
            <el-option 
              v-for="type in interactionTypeOptions" 
              :key="type.value" 
              :label="type.label" 
              :value="type.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联客户">
          <el-select 
            v-model="queryForm.customerId" 
            placeholder="请选择客户" 
            clearable
            style="width: 200px;"
          >
            <el-option 
              v-for="customer in customerOptions" 
              :key="customer.id" 
              :label="`${customer.name} (${customer.companyName})`" 
              :value="customer.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="recordsLoading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item style="margin-left: auto;">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增互动记录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-card class="common-table-card">
      <el-table 
        :data="interactionRecords" 
        style="width: 100%;" 
        v-loading="recordsLoading"
        :height="tableHeight"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="interactionType" label="互动类型" width="100">
          <template #default="scope">
            <el-tag 
              :type="getInteractionTypeTagType(scope.row.interactionType)"
            >
              {{ scope.row.interactionType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户姓名" min-width="120" />
        <el-table-column prop="customerCompany" label="客户公司" min-width="150" />
        <el-table-column prop="contentSummary" label="内容摘要" min-width="200">
          <template #default="scope">
            <el-tooltip 
              :content="scope.row.contentSummary" 
              placement="top"
              :disabled="scope.row.contentSummary.length <= 30"
            >
              <span>
                {{ scope.row.contentSummary.length > 30 ? 
                   scope.row.contentSummary.substring(0, 30) + '...' : 
                   scope.row.contentSummary }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="nextFollowTime" label="下次跟进时间" width="180">
          <template #default="scope">
            {{ scope.row.nextFollowTime ? formatDateTime(scope.row.nextFollowTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="common-pagination">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          small
        />
      </div>
    </el-card>
    
    <!-- 互动记录编辑/新增对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="600px"
      @close="resetForm"
    >
      <el-form 
        ref="recordFormRef" 
        :model="recordForm" 
        :rules="recordFormRules" 
        label-width="120px"
      >
        <el-form-item label="互动类型" prop="interactionType">
          <el-select 
            v-model="recordForm.interactionType" 
            placeholder="请选择互动类型"
            style="width: 100%;"
          >
            <el-option 
              v-for="type in interactionTypeOptions" 
              :key="type.value" 
              :label="type.label" 
              :value="type.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联客户" prop="customerId">
          <el-select 
            v-model="recordForm.customerId" 
            placeholder="请选择客户"
            style="width: 100%;"
            filterable
          >
            <el-option 
              v-for="customer in customerOptions" 
              :key="customer.id" 
              :label="`${customer.name} (${customer.companyName})`" 
              :value="customer.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容摘要" prop="contentSummary">
          <el-input 
            v-model="recordForm.contentSummary" 
            type="textarea"
            :rows="4"
            placeholder="请输入沟通内容的简要描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="下次跟进时间">
          <el-date-picker
            v-model="recordForm.nextFollowTime"
            type="datetime"
            placeholder="选择下次跟进时间"
            style="width: 100%;"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="common-dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { 
  getInteractionRecordList, 
  createInteractionRecord, 
  updateInteractionRecord, 
  deleteInteractionRecord,
  getInteractionRecordCustomers,
  getInteractionTypeOptions
} from '../utils/api'

export default {
  name: 'InteractionRecordManagement',
  components: {
    Plus,
    Search
  },
  setup() {
    const interactionRecords = ref([])
    const recordsLoading = ref(false)
    const dialogVisible = ref(false)
    const submitLoading = ref(false)
    const isEdit = ref(false)
    const recordFormRef = ref()
    
    // 下拉选项
    const interactionTypeOptions = ref([])
    const customerOptions = ref([])
    
    // 查询表单
    const queryForm = ref({
      interactionType: '',
      customerId: null
    })
    
    // 分页数据
    const pagination = ref({
      page: 1,
      size: 10,
      total: 0
    })
    
    // 计算表格高度
    const tableHeight = computed(() => {
      return 'calc(100vh - 284px)'
    })
    
    const recordForm = ref({
      id: null,
      interactionType: '',
      customerId: null,
      contentSummary: '',
      nextFollowTime: ''
    })
    
    const recordFormRules = {
      interactionType: [
        { required: true, message: '请选择互动类型', trigger: 'change' }
      ],
      customerId: [
        { required: true, message: '请选择关联客户', trigger: 'change' }
      ],
      contentSummary: [
        { required: true, message: '请输入内容摘要', trigger: 'blur' },
        { min: 5, max: 500, message: '内容摘要长度在 5 到 500 个字符', trigger: 'blur' }
      ]
    }
    
    const dialogTitle = computed(() => {
      return isEdit.value ? '编辑互动记录' : '新增互动记录'
    })
    
    // 获取互动类型标签样式
    const getInteractionTypeTagType = (type) => {
      switch (type) {
        case '电话': return 'success'
        case '邮件': return 'warning'
        case '会议': return 'primary'
        default: return ''
      }
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      return new Date(dateTime).toLocaleString('zh-CN')
    }
    
    // 加载互动记录列表
    const loadInteractionRecords = async () => {
      recordsLoading.value = true
      try {
        const params = {
          page: pagination.value.page,
          size: pagination.value.size
        }
        if (queryForm.value.interactionType) {
          params.interactionType = queryForm.value.interactionType
        }
        if (queryForm.value.customerId) {
          params.customerId = queryForm.value.customerId
        }
        
        const response = await getInteractionRecordList(params)
        if (response.data.code === 200) {
          const data = response.data.data
          interactionRecords.value = data.records || data
          pagination.value.total = data.total || interactionRecords.value.length
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('获取互动记录列表失败')
      } finally {
        recordsLoading.value = false
      }
    }
    
    // 加载下拉选项
    const loadOptions = async () => {
      try {
        // 加载互动类型选项
        const typeResponse = await getInteractionTypeOptions()
        if (typeResponse.data.code === 200) {
          interactionTypeOptions.value = typeResponse.data.data
        }
        
        // 加载客户选项
        const customerResponse = await getInteractionRecordCustomers()
        if (customerResponse.data.code === 200) {
          customerOptions.value = customerResponse.data.data
        }
      } catch (error) {
        ElMessage.error('加载选项失败')
      }
    }
    
    // 查询功能
    const handleSearch = () => {
      pagination.value.page = 1
      loadInteractionRecords()
    }
    
    // 重置查询
    const handleReset = () => {
      queryForm.value.interactionType = ''
      queryForm.value.customerId = null
      pagination.value.page = 1
      loadInteractionRecords()
    }
    
    // 分页大小改变
    const handleSizeChange = (newSize) => {
      pagination.value.size = newSize
      pagination.value.page = 1
      loadInteractionRecords()
    }
    
    // 当前页改变
    const handleCurrentChange = (newPage) => {
      pagination.value.page = newPage
      loadInteractionRecords()
    }
    
    // 新增互动记录
    const handleAdd = () => {
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑互动记录
    const handleEdit = (row) => {
      isEdit.value = true
      recordForm.value = {
        id: row.id,
        interactionType: row.interactionType,
        customerId: row.customerId,
        contentSummary: row.contentSummary,
        nextFollowTime: row.nextFollowTime
      }
      dialogVisible.value = true
    }
    
    // 删除互动记录
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(`确定要删除这条互动记录吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteInteractionRecord(row.id)
        if (response.data.code === 200) {
          ElMessage.success('删除成功')
          loadInteractionRecords() // 重新加载列表
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!recordFormRef.value) return
      
      try {
        await recordFormRef.value.validate()
        submitLoading.value = true
        
        let response
        if (isEdit.value) {
          // 编辑互动记录
          response = await updateInteractionRecord(recordForm.value.id, recordForm.value)
        } else {
          // 新增互动记录
          response = await createInteractionRecord(recordForm.value)
        }
        
        if (response.data.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          dialogVisible.value = false
          loadInteractionRecords() // 重新加载列表
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      recordForm.value = {
        id: null,
        interactionType: '',
        customerId: null,
        contentSummary: '',
        nextFollowTime: ''
      }
      if (recordFormRef.value) {
        recordFormRef.value.resetFields()
      }
    }
    
    onMounted(() => {
      loadOptions()
      loadInteractionRecords()
    })
    
    return {
      interactionRecords,
      recordsLoading,
      dialogVisible,
      submitLoading,
      recordForm,
      recordFormRules,
      recordFormRef,
      queryForm,
      pagination,
      tableHeight,
      dialogTitle,
      interactionTypeOptions,
      customerOptions,
      getInteractionTypeTagType,
      formatDateTime,
      loadInteractionRecords,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
/* 样式已移至全局样式文件 */
</style>